import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

/**
 * @Author: linzp
 * @Date: 2023/07/31/9:56
 */
public class demo07312 {

    public static void main(String[] args) {
        int corePoolSize = 10; // 线程池大小

        // 创建ScheduledExecutorService并设置异常处理器
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(corePoolSize, new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread t = new Thread(r);
                t.setUncaughtExceptionHandler(new CustomUncaughtExceptionHandler());
                return t;
            }
        });

        // 定义要执行的任务
        Runnable task = () -> {
            // 这里是要执行的任务逻辑
            System.out.println("Task executed by thread: " + Thread.currentThread().getName());
            // 抛出一个模拟的异常
            throw new RuntimeException("Simulated Exception");
        };

        // 延时时间
        long initialDelay = 5; // 5秒后执行任务
        long period = 10; // 任务执行间隔，10秒

        // 提交定时任务并设置定时周期
        scheduler.scheduleAtFixedRate(task, initialDelay, period, TimeUnit.SECONDS);
    }

    // 自定义异常处理器
    static class CustomUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            // 处理异常，可以记录日志等
            System.err.println("Exception caught in thread " + t.getName() + ": " + e.getMessage());
        }
    }
}


